<?php


namespace apps\marriage\core\logic;


use apps\marriage\core\model\UserPlatform;
use apps\marriage\core\service\SiteConfigService;
use apps\marriage\core\service\UserPlatformService;
use apps\marriage\core\service\UserService;
use think\Exception;
use think\facade\Log;
use vm\com\BaseService;
use vm\org\HttpUtil;
use vm\org\queue\QueueFactory;

class GoMessageLogic
{
    /**
     * @return UserService
     */
    protected function getUserService()
    {
        return service('User', SERVICE_NAMESPACE);
    }

    /**
     * @return UserPlatformService
     */
    protected function getUserPlatformService()
    {
        return service('UserPlatform', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|SiteConfigService
     */
    protected function getSiteConfigService()
    {
        return service('SiteConfig', SERVICE_NAMESPACE);
    }

    public function genUid($id)
    {
        $authKey = env('app_message.token');
        $hash = md5($id . $authKey);
        return substr($hash, 0, 16) . $id . substr($hash, 16);
    }

    public function send($sendUid, $toUid, $content)
    {
        try {
            $to = $this->genUid($toUid);
            $url = env('app_message.host');
            $post_data = [
                "token" => env('app_message.token'),
                "type" => 'publish',
                'to' => $to,
                "content" => $content
            ];

            $httpUtil = new HttpUtil();
            $result = $httpUtil->curl($url, HttpUtil::REQUEST_METHOD_POST, $post_data);
            $result = json_decode($result, true);
            if($result['error_code'] != 'ok') {
                if($result['error_code'] == 'offline') {    // 接收者已离线，发送到公众号、手机
                    try {
                        $userId = $toUid;
                        if($this->getUserPlatformService()->checkUserSubscribedMpAccount($userId)) {
                            $userPlatform = $this->getUserPlatformService()->info([
                                'user_id' => $userId,
                                'platform' => UserPlatform::PLATFORM_WX_MP
                            ]);
                            if($userPlatform) {
                                $sender = $this->getUserService()->getByPk($sendUid);
                                $openid = $userPlatform['open_id'];
                                $wechatConfig = config('wechat');
                                $msgTemplateId = $wechatConfig['mp_msg_templates']['visitor_service_remind'];
                                $msgData = [
                                    'first' => [
                                        'value' => '您有一条新的消息'
                                    ],
                                    'keyword1' => [
                                        'value' => $sender['nick']
                                    ],
                                    'keyword2' => [
                                        'value' => date('Y-m-d H:i:s')
                                    ],
                                    'remark' => [
                                        'value' => '请点击链接查看'
                                    ]
                                ];
                                $url = $this->getSiteConfigService()->getValueByCode('mp_site');
                                $miniprogram = null;

                                $queueConfig = config('queue');
                                $queueHandler = QueueFactory::instance();
                                $queueHandler->set($queueConfig['queues']['mp_msg'], [
                                    'openid' => $openid,
                                    'template_id' => $msgTemplateId,
                                    'data' => $msgData,
                                    'url' => $url,
                                    'miniprogram' => $miniprogram
                                ]);
                            }
                        }
                    } catch (\Exception $e) {
                        $log = 'FILE:' . $e->getFile() . "\r\n" . 'LINE:' . $e->getLine(). "\r\n" . 'MSG:' . $e->getMessage();
                        Log::error($log);
                    }
                } else {
                    Log::error('code: ' . $result['error_code'] . ' msg:' . $result['error_msg']);
                    throw new Exception('发送失败');
                }
            }
        } catch (\Exception $e) {
            $log = 'FILE:' . $e->getFile() . "\r\n" . 'LINE:' . $e->getLine(). "\r\n" . 'MSG:' . $e->getMessage();
            Log::error($log);
            throw new Exception('发送失败');
        }
        return true;
    }
}